package com.example.may;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import android.app.Activity;
import android.app.ActionBar;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
	private boolean isAppRunning = false;
	private String MY_PKG_NAME = "com.example.may01";//需要关闭的app包名
	private String uninstallapk1;
	private ActivityManager am;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
	    checkBrowser(MY_PKG_NAME);
	   if(runningApplicationsAll(MY_PKG_NAME)){
		    //杀死程序
	    	am.killBackgroundProcesses(MY_PKG_NAME);
	    	//通过包名删除相应的应用
	    	Uri packageURI = Uri.parse("package:"+ MY_PKG_NAME);   
	    	Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);   
	    	startActivity(uninstallIntent);
	    }  
	  
	}
	
	/**
	 * 判断应用是否存在
	 * @param packageName
	 * @return
	 */
	public boolean checkBrowser(String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = getPackageManager().getApplicationInfo(
                    packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }
	
	/**
	 * 遍历正在运行的所有程序
	 * @param packageName
	 * @return
	 */
	private boolean runningApplicationsAll(String packageName){
		//遍历正在运行的所有程序
		am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(100);
		for (RunningTaskInfo info : list) {
			if (info.topActivity.getPackageName().equals(packageName) && info.baseActivity.getPackageName().equals(packageName)) {
				return true;
			}
		}
		return false;
	}
}
